#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QIcon>
#include <QDebug>
#include <QFileInfo>
#include <QDir>
#include <QFile>
#include <QSerialPort>
#include <QThread>
#include <QTimer>

#include "utils/logger.h"
#include "utils/config.h"
#include "utils/settingsmanager.h"
#include "core/devicemanager.h"
#include "core/meter.h"
#include "core/alarmengine.h"
#include "model/metermodel.h"
#include "model/alarmmodel.h"
#include "model/historydatabridge.h"
#include "database/dbmanager.h"
#include "database/dataqueue.h"
#include "database/datamaintenance.h"
#include "io/serialportmanager.h"
#include "io/bemfaclient.h"

int main(int argc, char *argv[])
{
    // 注册元类型（用于跨线程信号槽）
    qRegisterMetaType<QSerialPort::SerialPortError>("QSerialPort::SerialPortError");

    // 设置应用程序属性
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    // 设置应用程序信息
    app.setOrganizationName("PowerCloud");
    app.setOrganizationDomain("powercloud.com");
    app.setApplicationName("QModbusPowerCloud");
    app.setApplicationVersion("1.0.0");

    // 初始化配置系统
    Config *config = Config::instance();
    QString configPath = "C:/Users/86188/Desktop/ModbusPro/QModbusPowerCloud/config/settings.ini";

    if (!config->initialize(configPath))
    {
        qWarning() << "无法加载配置文件:" << configPath;
    }

    // 初始化日志系统
    Logger *logger = Logger::instance();
    QString logPath = "C:/Users/86188/Desktop/ModbusPro/QModbusPowerCloud/logs/powercloud.log";
    QString logLevelStr = config->getLogLevel();
    bool consoleOutput = config->isLogConsoleEnabled();

    // 转换日志级别
    LogLevel logLevel = LogLevel::Info;
    if (logLevelStr == "Debug")
    {
        logLevel = LogLevel::Debug;
    }
    else if (logLevelStr == "Info")
    {
        logLevel = LogLevel::Info;
    }
    else if (logLevelStr == "Warning")
    {
        logLevel = LogLevel::Warning;
    }
    else if (logLevelStr == "Error")
    {
        logLevel = LogLevel::Error;
    }
    else if (logLevelStr == "Critical")
    {
        logLevel = LogLevel::Critical;
    }

    // 确保日志目录存在
    QFileInfo logFileInfo(logPath);
    QDir logDir = logFileInfo.absoluteDir();
    if (!logDir.exists())
    {
        logDir.mkpath("."); // 创建日志目录
    }

    logger->initialize(logPath, logLevel, consoleOutput);

    LOG_INFO("========================================");
    LOG_INFO("智慧配电云监控系统启动");
    LOG_INFO(QString("版本: %1").arg(app.applicationVersion()));
    LOG_INFO(QString("日志级别: %1").arg(logLevelStr));
    LOG_INFO("========================================");

    // 初始化数据库
    DBManager *dbManager = DBManager::instance();
    QString dbPath = "C:/Users/86188/Desktop/ModbusPro/QModbusPowerCloud/data/powercloud.db";
    if (!dbManager->initialize(dbPath))
    {
        LOG_ERROR("数据库初始化失败");
    }
    else
    {
        LOG_INFO("数据库初始化成功: " + dbPath);
    }

    // 创建串口管理器
    SerialPortManager *portManager = new SerialPortManager();

    // 创建设备管理器
    DeviceManager *deviceManager = new DeviceManager(portManager);

    // 创建数据队列（用于历史数据缓存和批量存储）
    DataQueue *dataQueue = new DataQueue(dbManager);
    dataQueue->startAutoFlush(300000); // 每5分钟自动刷新到数据库
    dataQueue->setMaxQueueSize(10000); // 队列最大10000条数据
    LOG_INFO("数据队列已创建，自动刷新间隔: 5分钟，最大队列: 10000条");

    // 连接设备管理器的采样信号到数据队列
    QObject::connect(deviceManager, &DeviceManager::meterDataSampled,
                     [dataQueue](int meterId, Meter *meter)
                     {
                         if (!meter || !meter->isOnline())
                         {
                             return;
                         }

                         // 构造历史数据
                         HistoryData data;
                         data.meterId = meterId;
                         data.ua = meter->ua();
                         data.ub = meter->ub();
                         data.uc = meter->uc();
                         data.ia = meter->ia();
                         data.ib = meter->ib();
                         data.ic = meter->ic();
                         data.timestamp = QDateTime::currentDateTime();

                         // 加入队列
                         dataQueue->enqueue(data);
                     });

    LOG_INFO("数据采集信号已连接到数据队列");

    // 创建数据维护管理器（定时清理过期数据）
    DataMaintenance *dataMaintenance = new DataMaintenance(dbManager);
    dataMaintenance->setHistoryRetentionDays(90); // 保留90天历史数据
    dataMaintenance->setAlarmRetentionDays(180);  // 保留180天报警记录
    dataMaintenance->startAutoMaintenance(24);    // 每24小时检查一次
    LOG_INFO("数据维护管理器已启动，历史数据保留90天，每24小时检查一次");

    // 创建报警引擎
    AlarmEngine *alarmEngine = new AlarmEngine(dbManager);
    alarmEngine->start();

    // ========== 创建巴法云客户端 ==========
    BemfaClient *bemfaClient = nullptr;

    // 检查是否启用巴法云推送
    if (config->isBemfaEnabled())
    {
        bemfaClient = new BemfaClient();

        // 从配置文件读取巴法云参数
        QString bemfaHost = config->getBemfaHost();
        int bemfaPort = config->getBemfaPort();
        QString bemfaUid = config->getBemfaUid();

        // 初始化巴法云客户端
        if (bemfaClient->initialize(bemfaHost, bemfaPort, bemfaUid))
        {
            LOG_INFO(QString("巴法云客户端初始化成功 - 服务器: %1:%2").arg(bemfaHost).arg(bemfaPort));

            // 配置3个配电室主题
            BemfaClient::RoomInfo roomA{
                1,                        // roomId
                "配电室A",                // roomName
                config->getBemfaTopic1(), // topic
                1,                        // startMeterId
                40                        // endMeterId
            };

            BemfaClient::RoomInfo roomB{
                2,
                "配电室B",
                config->getBemfaTopic2(),
                41,
                80};

            BemfaClient::RoomInfo roomC{
                3,
                "配电室C",
                config->getBemfaTopic3(),
                81,
                120};

            bemfaClient->addRoomConfig(roomA);
            bemfaClient->addRoomConfig(roomB);
            bemfaClient->addRoomConfig(roomC);

            LOG_INFO(QString("配电室主题配置完成: %1, %2, %3")
                         .arg(config->getBemfaTopic1())
                         .arg(config->getBemfaTopic2())
                         .arg(config->getBemfaTopic3()));

            // 关联设备管理器和报警引擎
            bemfaClient->setDeviceManager(deviceManager);
            bemfaClient->setAlarmEngine(alarmEngine);

            // 连接到巴法云服务器
            bemfaClient->connectToServer();

            // 启动自动推送
            int dataPushInterval = config->getBemfaDataPushInterval();
            int fullDataUploadInterval = config->getBemfaFullDataUploadInterval();
            bemfaClient->startAutoPush(dataPushInterval, fullDataUploadInterval);

            LOG_INFO(QString("巴法云推送已启动 - 汇总数据: %1秒, 全量数据: %2秒, 报警: 即时推送")
                         .arg(dataPushInterval)
                         .arg(fullDataUploadInterval));
        }
        else
        {
            LOG_ERROR("巴法云客户端初始化失败，请检查配置文件中的UID是否正确");
            delete bemfaClient;
            bemfaClient = nullptr;
        }
    }
    else
    {
        LOG_INFO("巴法云推送未启用，如需远程监控请在配置文件中设置 Bemfa/Enabled=true");
    }

    // 从配置文件加载总线配置
    QString bus1Port = config->getSerialPort1();
    QString bus2Port = config->getSerialPort2();
    QString bus3Port = config->getSerialPort3();

    LOG_INFO(QString("配置总线 - Bus1: %1, Bus2: %2, Bus3: %3").arg(bus1Port).arg(bus2Port).arg(bus3Port));

    // 配置3条总线（配电室A、B、C）
    if (!bus1Port.isEmpty())
    {
        DeviceManager::BusConfig busA;
        busA.busId = 1;
        busA.busName = "配电室A";
        busA.portName = bus1Port;
        busA.startSlaveId = 1;
        busA.endSlaveId = 40;
        deviceManager->addBusConfig(busA);
    }

    if (!bus2Port.isEmpty())
    {
        DeviceManager::BusConfig busB;
        busB.busId = 2;
        busB.busName = "配电室B";
        busB.portName = bus2Port;
        busB.startSlaveId = 41;
        busB.endSlaveId = 80;
        deviceManager->addBusConfig(busB);
    }

    if (!bus3Port.isEmpty())
    {
        DeviceManager::BusConfig busC;
        busC.busId = 3;
        busC.busName = "配电室C";
        busC.portName = bus3Port;
        busC.startSlaveId = 81;
        busC.endSlaveId = 120;
        deviceManager->addBusConfig(busC);
    }

    // 创建电表数据模型
    MeterModel *meterModel = new MeterModel(deviceManager);

    // 连接批量更新信号（用于UI刷新优化）
    QObject::connect(deviceManager, &DeviceManager::meterDataBatchUpdated,
                     meterModel, &MeterModel::onMeterDataBatchUpdated);

    LOG_INFO("批量更新信号已连接到MeterModel，UI刷新已优化");

    // 创建报警数据模型
    AlarmModel *alarmModel = new AlarmModel(alarmEngine);

    // 创建历史数据桥接
    HistoryDataBridge *historyDataBridge = new HistoryDataBridge(dbManager);

    // 创建设置管理器
    SettingsManager *settingsManager = new SettingsManager(config, portManager, deviceManager);

    // 加载 QML 引擎
    QQmlApplicationEngine engine;

    // 注册 C++ 类型到 QML
    qmlRegisterUncreatableType<Meter>("PowerCloud", 1, 0, "Meter", "Meter cannot be created from QML");
    qmlRegisterUncreatableType<DeviceManager>("PowerCloud", 1, 0, "DeviceManager", "DeviceManager cannot be created from QML");
    qmlRegisterUncreatableType<MeterModel>("PowerCloud", 1, 0, "MeterModel", "MeterModel cannot be created from QML");
    qmlRegisterUncreatableType<AlarmEngine>("PowerCloud", 1, 0, "AlarmEngine", "AlarmEngine cannot be created from QML");
    qmlRegisterUncreatableType<AlarmModel>("PowerCloud", 1, 0, "AlarmModel", "AlarmModel cannot be created from QML");

    // 注册配置、日志、设备管理器和模型到 QML 上下文
    engine.rootContext()->setContextProperty("config", config);
    engine.rootContext()->setContextProperty("logger", logger);
    engine.rootContext()->setContextProperty("portManager", portManager);
    engine.rootContext()->setContextProperty("deviceManager", deviceManager);
    engine.rootContext()->setContextProperty("settingsManager", settingsManager);
    engine.rootContext()->setContextProperty("meterModel", meterModel);
    engine.rootContext()->setContextProperty("alarmEngine", alarmEngine);
    engine.rootContext()->setContextProperty("alarmModel", alarmModel);
    engine.rootContext()->setContextProperty("dbManager", dbManager);
    engine.rootContext()->setContextProperty("historyDataBridge", historyDataBridge);
    engine.rootContext()->setContextProperty("bemfaClient", bemfaClient);

    // 加载主 QML 文件
    const QUrl url(QStringLiteral("qrc:/main.qml"));

    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl)
                     {
            if (!obj && url == objUrl) {
                qCritical() << "无法加载 QML 文件";
                QCoreApplication::exit(-1);
            } }, Qt::QueuedConnection);

    engine.load(url);

    if (engine.rootObjects().isEmpty())
    {
        qCritical() << "QML 引擎加载失败";
        return -1;
    }

    LOG_INFO("界面加载成功");

    // 不自动启动，让用户在界面手动启动
    LOG_INFO("系统已就绪，请在设置页面手动启动系统");

    // 进入主循环
    int result = app.exec();

    // 程序退出
    LOG_INFO("程序正常退出");

    // 清理资源
    // 先停止巴法云推送
    if (bemfaClient)
    {
        bemfaClient->stopAutoPush();
        bemfaClient->disconnectFromServer();
        delete bemfaClient;
        LOG_INFO("巴法云客户端已关闭");
    }

    delete historyDataBridge;
    delete alarmModel;
    delete meterModel;
    delete settingsManager;
    delete alarmEngine;
    delete dataMaintenance;
    delete dataQueue; // 析构时会自动刷新剩余数据
    delete deviceManager;
    delete portManager;

    dbManager->close();
    logger->close();

    return result;
}
